﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.IO.Ports;

namespace KeystrokeConverter
{
    public class ComConfig
    {
        #region FileIO
        private static ComConfig _instance;
        
        public static ComConfig Instance
        {
            get
            {
                if (_instance == null)
                {
                    tryLoadConfig();
                }
                return _instance;
            }
        }

        private ComConfig()
        {
            _portName = "COM3";
            _baudRate = 9600;
            _portParity = Parity.None;
            _dataBits = 8;
            _sbits = StopBits.One;
        }

        private static void tryLoadConfig()
        {
            string AssemblyDirectory = Path.GetDirectoryName(System.Reflection.Assembly.GetAssembly(typeof(ComConfig)).Location);
            string ConfigLocatoin = AssemblyDirectory + "\\config.xml";
            try
            {
                using (TextReader reader = new StreamReader(ConfigLocatoin))
                {
                    XmlSerializer loader = new XmlSerializer(typeof(ComConfig));
                    _instance = (ComConfig) loader.Deserialize(reader);
                }
            }
            catch
            {
                _instance = new ComConfig();
                saveConfig(ConfigLocatoin);
            }

        }

        private static void saveConfig(string path)
        {
            using (TextWriter writer = new StreamWriter(path))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(ComConfig));
                serializer.Serialize(writer, _instance);
            }
        }
        #endregion
        #region Accessors
        private string _portName;
        private int _baudRate;
        private Parity _portParity;
        private int _dataBits;
        private StopBits _sbits;

        [XmlElement]
        public string PortName { get { return _portName; } set { _portName = value; } }

        [XmlElement]
        public int BaudRate { get { return _baudRate; } set { _baudRate = value; } }

        [XmlElement]
        public Parity PortParity { get { return _portParity; } set { _portParity = value; } }

        [XmlElement]
        public int DataBits { get { return _dataBits; } set { _dataBits = value; } }

        [XmlElement]
        public StopBits SBits { get { return _sbits; } set { _sbits = value; } }
        #endregion
    }
}
